﻿using System;
using System.ComponentModel;

namespace Utility
{
    [TypeConverter(typeof(UnixTimestampClassConverter))]
    public class UnixTimestamp
    {
        private readonly static DateTimeOffset Epoch = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);

        private readonly DateTimeOffset _time;

        public UnixTimestamp()
        {
            _time = DateTimeOffset.MinValue;
        }

        public UnixTimestamp(long msec)
        {
            _time = Epoch.AddSeconds(msec / 1000.0);
        }

        public static implicit operator UnixTimestamp(long msec)
        {
            return new UnixTimestamp(msec);
        }

        public static implicit operator long(UnixTimestamp value)
        {
            return (long)(value._time - Epoch).TotalMilliseconds;
        }

        public static implicit operator DateTime(UnixTimestamp value)
        {
            return value._time.DateTime;
        }

        public long TotalMilliseconds
        {
            get { return (long) (_time.UtcDateTime - Epoch).TotalMilliseconds; }
        }

        public override string ToString()
        {
            return _time.ToString();
        }
    }

    class UnixTimestampClassConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string) || sourceType == typeof(long))
                return true;
            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (value is string)
                return new UnixTimestamp(long.Parse((string) value));
            if (value is long)
                return new UnixTimestamp((long) value);
            return base.ConvertFrom(context, culture, value);
        }

    }

}
